#include "chargingmodel.h"

ChargingModel::ChargingModel( QObject* parent ) {
    qDebug() << "ChargingModel";
    _qsocket = new QTcpSocket( this );
    t        = new QTimer();
    connect( t, SIGNAL( timeout() ), this, SLOT( sltTimeOut() ) );
}

ChargingModel::~ChargingModel() {}

bool ChargingModel::isConnected() {
    qDebug() << _qsocket << _qsocket->isOpen() << _qsocket->isValid();
    if ( _qsocket && _qsocket->isOpen() && _qsocket->isValid() ) {
        if ( _qsocket->peerName() != ip && _qsocket->peerPort() != port ) { emit sigSendTips( QString( "opensocket %1:%2" ).arg( _qsocket->peerName(), _qsocket->peerPort() ) ); }
        return true;
    }
    return false;
}

void ChargingModel::onTcpConnected() {
    emit sigSendTips( "充电桩tcp 连接成功！" );
    if ( _qsocket->peerName() != ip && _qsocket->peerPort() != port ) { emit sigSendTips( QString( "opensocket : [%1:%2] " ).arg( _qsocket->peerName(), _qsocket->peerPort() ) ); }
    tcpConnected = true;
    //    t->start( 2000 );

    if ( outAction == STOP ) { chargingStop(); }
    if ( outAction == OPEN ) { chargingOpen(); }
    if ( outAction == CLOSE ) { chargingClose(); }
}
void ChargingModel::onTcpDisconnected() {
    emit sigSendTips( "充电桩tcp 断开！" );
    t->stop();
    tcpConnected = false;
    _qsocket->abort();
}

void ChargingModel::tcpOpen( const QString& ip, unsigned short port ) {
    if ( isConnected() ) {
        qDebug() << "充电桩打开成功！";
        emit sigSendTips( "充电桩tcp 打开成功！" );
    }
    else {
        try {
            _qsocket->connectToHost( ip, port );
            connect( _qsocket, SIGNAL( connected() ), this, SLOT( onTcpConnected() ) );
            connect( _qsocket, SIGNAL( disconnected() ), this, SLOT( onTcpDisconnected() ) );
            connect( _qsocket, SIGNAL( readyRead() ), this, SLOT( onTcpReadyRead() ) );
        }
        catch ( ... ) {
            emit sigSendTips( "充电桩tcp 打失败！" );
        }
    }
}

bool ChargingModel::chargingOpen() {
    qDebug() << "ChargingModel:chargingOpen";
}

bool ChargingModel::chargingClose() {}

bool ChargingModel::chargingStop() {}

void ChargingModel::tcpClose() {
    t->stop();
    tcpConnected = false;
    outAction    = UNKONWN;
    isFinish     = false;
    disconnect( _qsocket, SIGNAL( connected() ), this, SLOT( onTcpConnected() ) );
    disconnect( _qsocket, SIGNAL( disconnected() ), this, SLOT( onTcpDisconnected() ) );
    disconnect( _qsocket, SIGNAL( readyRead() ), this, SLOT( onTcpReadyRead() ) );

    _qsocket->abort();
    emit sigSendTips( "充电桩tcp 断开！" );
}

void ChargingModel::onTcpReadyRead() {
    qDebug() << "CharginModel Ready";
}

void ChargingModel::sltTimeOut() {
    qDebug() << "CharginModel sltTimeOut";
}
